// src/api/riskApi.js

import axios from 'axios';

/**
 * 批量获取用户所有资产的风险评分
 * GET /api/risk/scores?userid=<用户ID>
 * 返回：{ code:0, data:[ { id, risk_score }, … ] }
 */

/**
 * 从 localStorage 获取用户 ID
 * @returns {string} - 用户 ID
 */
const getUserId = () => {
  const userInfo = localStorage.getItem('user_info');
  if (!userInfo) throw { msg: '用户未登录或未找到用户信息' };

  try {
      const parsedUserInfo = JSON.parse(userInfo);
      return parsedUserInfo.id;
  } catch (error) {
      throw { msg: '用户信息解析失败' };
  }
};



export const $getRiskScores = async () => {
  try {
    const userid = getUserId();
    const response = await axios.get(`/api/stock_scores?userid=${userid}`);
    console.log('用户id:', userid)
    const body = response.data;
    console.log('响应数据:', body);
    if (body.code === 0) {
      return body.data;
    }
    throw { msg: body.msg || '获取风险评分失败' };
  } catch (error) {
    throw error.response?.data || { msg: error.msg || '网络错误' };
  }
};

/**
 * 获取单个资产的风险详细拆解
 * GET /api/risk/asset/<assetId>
 * 返回：{ code:0, data:{ id, type, products_id, quantity, buy_price, risk_score, factors } }
 */
export const $getAssetRiskDetail = async (assetId) => {
  try {
    const response = await axios.get(`/api/risk/asset/${assetId}`);
    const body = response.data;
    if (body.code === 0) {
      return body.data;
    }
    throw { msg: body.msg || '获取资产风险详情失败' };
  } catch (error) {
    throw error.response?.data || { msg: error.msg || '网络错误' };
  }
};


export const $getStockRiskScores = async () => {
  try {
    const userid = getUserId();
    const response = await axios.get('/api/risk/stock_scores',{
      params:{userid },
        headers: {
          Authorization: `Bearer ${localStorage.getItem('jwt_token')}`
        }
    });
    console.log('用户id:', userid)
    const body = response.data;
    console.log('响应数据:', body);
    if (body.code === 0) {
      return body.data;
    }
    throw { msg: body.msg || '获取风险评分失败' };
  } catch (error) {
    throw error.response?.data || { msg: error.msg || '网络错误' };
  }
};

/**
 * 获取单个资产的风险详细拆解
 * GET /api/risk/asset/<assetId>
 * 返回：{ code:0, data:{ id, type, products_id, quantity, buy_price, risk_score, factors } }
 */
export const $getStockRiskDetail = async (assetId) => {
  try {
    const response = await axios.get(`/api/risk/stock/${assetId}`,{
      headers: {
        Authorization: `Bearer ${localStorage.getItem('jwt_token')}`
      }
    });
    const body = response.data;
    console.log('Stock响应数据:', body);
    if (body.code === 0) {
      return body.data;
    }
    throw { msg: body.msg || '获取资产风险详情失败' };
  } catch (error) {
    throw error.response?.data || { msg: error.msg || '网络错误' };
  }
};

